package com.kkaheng.grid.demo;

import android.app.Activity;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.Toast;

import com.kkaheng.grid.view.GridView;
import com.kkaheng.grid.view.cell.Cell;
import com.kkaheng.grid.view.cell.CellAdapter;
import com.kkaheng.grid.view.cell.TextCell;

import java.util.Locale;
import java.util.Random;

/**
 * 虚假人员数据表：10 列 × 101 行（含表头）
 */
public class MainActivity extends Activity {

    /* ------------------ 常量 ------------------ */
    private static final int COL = 51;
    private static final int ROW = 51;
    private static final int TYPE_HEADER = 0;
    private static final int TYPE_NORMAL = 1;

    /* ------------------ 数据 ------------------ */
    private final String[][] cellData = new String[COL][ROW];
    private final float[] colWidths  = new float[COL];
    private final float[] rowHeights = new float[ROW];
    private final Random r = new Random(System.currentTimeMillis());
    
    private Toast t;
    
    public void postText(CharSequence text) {
    	if (t != null) {
            t.cancel();
        }
        t = Toast.makeText(this, text, Toast.LENGTH_LONG);
        t.show();
    }

    /* ------------------ 生命周期 ------------------ */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
        /* 1. 生成数据 */
        generateAllData();
        /* 2. 计算宽高 */
        measureSizes();

        /* 3. GridView */
        GridView grid = new GridView(this);
        grid.setScrollable(true);
        grid.setScalable(true);
        grid.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));

        grid.setAdapter(new CellAdapter() {
            @Override public Object getData(int c, int r) { return cellData[c][r]; }
            @Override public int getColumnCount()           { return COL; }
            @Override public int getRowCount()              { return ROW; }
            @Override public float getWidth(int c)          { return colWidths[c]; }
            @Override public float getHeight(int r)         { return rowHeights[r]; }
            @Override public int getItemType(int c, int r)  { return r == 0 || c == 0 ? TYPE_HEADER : TYPE_NORMAL; }

            @Override public Cell onCreateCell(int type)    { return createTextCell(type); }

            @Override public boolean isTouchable(int c, int r) { return r != 0; }
            @Override public void onClick(int c, int r) {
                postText("单击了 第" + (c + 1) + "行，" +
                    "第" + (r + 1) + "列：" +
                    String.valueOf(getData(c, r)));
            }
            @Override public void onLongClick(int c, int r) {
                postText("长按了 第" + (c + 1) + "行，" +
                    "第" + (r + 1) + "列：" +
                    String.valueOf(getData(c, r)));
            }
        });

        setContentView(grid);
        } catch(Exception e) {
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    private void generateAllData() {
        for (int c = 0; c < COL; c++) {
            for (int r = 0; r < ROW; r++) {
                String data;
                if (c == 0 && r == 0) {
                    data = "-";
                } else if (r == 0) {
                    data = c + "列";
                } else if (c == 0) {
                    data = r + "行";
                } else {
                    data = String.format("%,d", this.r.nextInt(100000));
                }
                cellData[c][r] = data;
            }
        }
    }

    /* ------------------ 尺寸测量 ------------------ */
    private void measureSizes() {
        TextCell measureCell = new TextCell();
        measureCell.setTextSize(dp(13));
        float pd = dp(10);
        measureCell.setPadding(pd, pd, pd, pd);

        for (int c = 0; c < COL; c++) {
            float max = 0;
            for (int r = 0; r < ROW; r++) {
                max = Math.max(max, measureCell.measureWidth(cellData[c][r]));
            }
            colWidths[c] = max;
        }

        for (int r = 0; r < ROW; r++) {
            float max = 0;
            for (int c = 0; c < COL; c++) {
                max = Math.max(max, measureCell.measureHeight(cellData[c][r]));
            }
            rowHeights[r] = max;
        }
    }

    /* ------------------ 单元格样式 ------------------ */
    private TextCell createTextCell(int type) {
        TextCell cell = new TextCell();
        float pd = dp(10);
        cell.setTextSize(dp(13));
        cell.setPadding(pd, pd, pd, pd);

        if (type == TYPE_HEADER) {
            cell.setBackgroundColor(Color.parseColor("#E0E0E0"));
            cell.setTextColor(Color.BLACK);
            cell.setGravity(Gravity.CENTER);
            cell.setBorderWidth(1.5f);
            cell.setBorderColor(Color.LTGRAY);
        } else {
            cell.setBackgroundColor(Color.WHITE);
            cell.setTextColor(Color.DKGRAY);
            cell.setGravity(Gravity.LEFT);
            cell.setBorderWidth(1f);
            cell.setBorderColor(0xFFDADADA);
        }
        return cell;
    }

    /* ------------------ 工具 ------------------ */
    private float dp(float dp) {
        return TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP,
                dp,
                getResources().getDisplayMetrics());
    }
}
